package com.xjm.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xjm.entity.model.TrackingModel;

import java.util.Date;
import java.util.Optional;

// apispace网站接口枚举 https://www.apispace.com/
public class SpaceApiUtil {

    private static final String PREFIX = "https://eolink.o.apispace.com/wlgj1/paidtobuy_api";

    private static final String API_TOKEN = "adj4ulr9rxma7rcn9w3q2zxibiquuv1m";

    //智能识别电子面单号 [查询不扣费]
    public static String getOrderType(String orderNumber) {
        String url = PREFIX + "/mail_discern";
        try (HttpResponse execute = HttpUtil.createPost(url)
                .header("X-APISpace-Token", API_TOKEN)
                .body("{\"mailNo\":\"" + orderNumber + "\"}")
                .execute()) {
            if (execute.getStatus() == 200) {
                JSON body = JSONUtil.parse(execute.body());
                JSONArray expressCompanyList = Optional.ofNullable(body.getByPath("expressCompanyList", JSONArray.class)).orElse(new JSONArray());
                if (!expressCompanyList.isEmpty()) {
                    return expressCompanyList.get(0, JSON.class).getByPath("cpCode", String.class);
                }
            }
            return "";
        }
    }

    //实时快递查询
    public static TrackingModel getOrderStatus(String orderNumber, String cpCode) {
        TrackingModel trackingModel = new TrackingModel();
        String url = PREFIX + "/trace_search";
        try (HttpResponse execute = HttpUtil.createPost(url)
                .header("X-APISpace-Token", API_TOKEN)
                .body("{\"mailNo\":\"" + orderNumber + "\",\"cpCode\":\"" + cpCode + "\"}")
                .execute()) {
            if (execute.getStatus() == 200) {
                JSON logisticsTrace = JSONUtil.parseObj(execute.body())
                        .getByPath("logisticsTrace", JSON.class);
                if (logisticsTrace != null) {
                    JSONArray trace = logisticsTrace.getByPath("logisticsTraceDetailList", JSONArray.class);
                    String logisticsStatusDesc = logisticsTrace.getByPath("logisticsStatusDesc", String.class);
                    Date theLastTime = logisticsTrace.getByPath("theLastTime", Date.class);
                    if (ObjectUtil.isAllNotEmpty(trace, logisticsStatusDesc, theLastTime)) {
                        trackingModel.setEnd(logisticsStatusDesc.equals("已签收") ? 1 : 0);
                        trackingModel.setTrace(trace.toString());
                        trackingModel.setTheLastTime(theLastTime);
                        return trackingModel;
                    }
                }
            }
            return null;
        }
    }
}
